/*
 * @Author: Jone XIn
 * @Date: 2022-01-10 21:18:20
 * @LastEditTime: 2022-01-16 09:51:33
 * @Description: 监听文件改变类
 */
const fs = require('fs-extra');
const md5 = require('md5');
const path = require('path');
const { deviceSeq, Device } = require('../model/device');
const { uploadNewsFileBuffer } = require('../http/axios');
const { web_socket_config } = require('../config.json');
const Client = require('../lib/ws_client');

class WatchFile {
    preveMd5 = null; //
    fsWait = false;  // 延时时间
    watchPath = []; // 项目路径数组
    static flagCount = 0;

    constructor(callback) {
        // 初始化websocket客户端
        this.client = Client(web_socket_config.ip, web_socket_config.port, (ws) => {
            callback(ws)
        });
    }
    /**
     * 监控项目
     * 递归选项仅在 macOS 和 Windows 上受支持
     * @param {Object} deviceInfo 监控信息
     * @returns Boolen
     */
    startWatchFile(deviceInfo) {
        try {
            // 监控文件夹filePath下所有文件变动
            const { filePath, sync_id } = deviceInfo;
            let watcher = fs.watch(filePath, { recursive: true }, (event, filename) => {
                if (filename) {
                    // 文件的绝对路径
                    const updateFilePath = filePath + '/' + filename;
                    // 忽略的文件/文件夹[暂时自动忽略-node-modules 和 package-lock.json]
                    if (updateFilePath.includes(filePath + 'node_modules/') || updateFilePath.includes(filePath + 'package-lock.json')) return;
                    // 跟新间隔 2s
                    if (this.fsWait) return;
                    this.fsWait = setTimeout(() => {
                        this.fsWait = false;
                    }, 2000)

                    if (WatchFile.flagCount != 0) {
                        WatchFile.flagCount = 0
                        return;
                    }
                    if (event == 'rename') {
                        // 判断文件是否存在【 存在--> 增加 】 【不存砸 --> 删除】
                        if (!fs.pathExistsSync(updateFilePath)) { // 删除
                            console.log(`${updateFilePath}文件删除`);
                            this.client.sendNewsText({
                                sync_id: sync_id,
                                data: '',
                                type: 'delete',
                                filePath: updateFilePath
                            });
                            return;
                        }
                    }
                    let fileBuffer = '', is_file = false;
                    // 判断是否是文件
                    if (fs.statSync(updateFilePath).isFile()) {
                        // 查看是否更新
                        let currentMd5 = md5(fs.readFileSync(updateFilePath))
                        if (currentMd5 == this.preveMd5) {
                            console.log('文件无更新');
                            return false;
                        }
                        console.log(`e: ${event} path: ${updateFilePath}更新`);
                        this.preveMd5 = currentMd5
                        // 发送到房间【包含 修改 和 增加】
                        fileBuffer = fs.readFileSync(updateFilePath);
                        is_file = true;
                    }

                    this.client.sendNewsText({
                        sync_id: sync_id,
                        data: fileBuffer,
                        type: 'update',
                        filePath: updateFilePath,
                        is_file
                    });
                }
            })
            watcher.on('error', err => {
                console.log(err);
            })
            watcher.on('close', () => {
                console.log('wacher关闭');
            })
            return true;
        } catch (_) {
            console.log(_);
            return _;
        }
    }

    // 在服务端注册本地监听信息
    registProject(projectInfo) {
        this.client.registRoomId(projectInfo);
    }
}

module.exports = WatchFile;
